package command;

import human.User;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jdbc.UserDao;

import org.apache.log4j.Logger;

public class LoginCommand implements Command {
	public static final String SESS_AUTH = "auth";

	private static final Logger log = Logger.getLogger(LoginCommand.class.getName());

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) {

		String email;
		String password;
		String redirectUrl = null;
		final String message;
		email = request.getParameter("email");
		password = request.getParameter("password");
		UserDao userDao = new UserDao();
		try {
			userDao.close();
			userDao.start();

			User user = userDao.selectUserByEmailAndPassword(email, password);

			if (user != null) {
				HttpSession sess = request.getSession(true);
				sess.setAttribute(SESS_AUTH, Boolean.TRUE);
				sess.setMaxInactiveInterval(10*60);
				sess.setAttribute("userId", user.getId());
				request.setAttribute("user", user);
				message = "Authorized!";
				redirectUrl = "/home.jspx";
			} else {
				message = "Not Authorized!";
				redirectUrl = "/login.jspx";
			}
			renderRedirectWithMessage(response, redirectUrl, message);
		} catch (IOException e) {
			log.error("can't redirect ", e);
		}finally {
			userDao.close();
		}
		return redirectUrl;
	}

	protected void renderRedirectWithMessage(HttpServletResponse resp, String redirectUrl, String message)
			throws IOException {
		final PrintWriter w = resp.getWriter();
		w.print("<html>");
		w.print("<head><META HTTP-EQUIV=Refresh CONTENT=\"2; URL=" + redirectUrl + "\"/></head>");
		w.print("<body style=\"text-align: center\">" + message + "</body>");
		w.print("</html>");
	}
}
